import { ref, reactive, onMounted, h, toRaw } from "vue";
import { taskStrategyApi, taskTypeApi } from "@/api/task";
import { customerGradeApi } from "@/api/crm";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import { usePublicHooks } from "@/views/system/hooks";
import editForm from "../form.vue";

export function useTaskStrategies(tableRef) {
  const form = reactive({
    strategy_name: "",
    status: "",
    page: 1,
    limit: 15
  });

  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const selectedNum = ref(0);
  const gradeList = ref([]);
  const taskTypeList = ref([]);
  const { tagStyle } = usePublicHooks();

  const pagination = reactive({
    total: 0,
    pageSize: 15,
    pageSizes: [10, 20, 40, 60, 100, 200],
    currentPage: 1,
    background: true
  });

  const columns = ref([
    { label: "勾选列", type: "selection", width: 50, fixed: true },
    { 
      label: "策略ID", 
      prop: "id", 
      width: 80, 
      align: "center",
      fixed: true
    },
    { 
      label: "策略名称", 
      prop: "strategy_name", 
      width: 180,
      showOverflowTooltip: true
    },
    { 
      label: "客户等级", 
      prop: "customer_grade.name", 
      width: 120,
      align: "center"
    },
    { 
      label: "任务类型", 
      prop: "task_type.name", 
      width: 150,
      showOverflowTooltip: true
    },
    { 
      label: "自动指派频率", 
      prop: "frequency_text", 
      width: 160,
      align: "center",
      cellRenderer: ({ row }) => {
        return h("el-tag", {
          type: "info",
          size: "small",
          style: tagStyle.value(0)
        }, row.frequency_text || "未设置");
      }
    },
    { 
      label: "状态", 
      prop: "status", 
      width: 100,
      align: "center",
      cellRenderer: ({ row }) => {
        return h("el-tag", {
          type: row.status === 1 ? "success" : "danger",
          size: "small",
          style: tagStyle.value(row.status)
        }, row.status === 1 ? "启用" : "禁用");
      }
    },
    { 
      label: "创建时间", 
      prop: "created_at", 
      width: 160,
      sortable: "custom"
    },
    { 
      label: "操作", 
      fixed: "right", 
      width: 220, 
      slot: "operation" as const
    }
  ] as any);

  function resetForm(formEl?) {
    if (formEl) {
      formEl.resetFields();
    } else {
      Object.assign(form, {
        strategy_name: "",
        status: "",
        page: 1,
        limit: 15
      });
    }
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    try {
      const params = {
        ...toRaw(form),
        page: pagination.currentPage,
        limit: pagination.pageSize
      };
      
      const { data } = await taskStrategyApi.list(params);
      dataList.value = data.data || [];
      pagination.total = data.total || 0;
    } catch (error) {
      console.error("获取策略列表失败:", error);
      message("获取数据失败", { type: "error" });
    } finally {
      loading.value = false;
    }
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  function handleSelectionChange(selection) {
    selectedNum.value = selection.length;
  }

  function onSelectionCancel() {
    tableRef.value.getTableRef().clearSelection();
    selectedNum.value = 0;
  }

  // 获取选项数据
  async function loadOptions() {
    try {
      const [gradeRes, taskTypeRes] = await Promise.all([
        customerGradeApi.list(),
        taskTypeApi.list()
      ]);
      gradeList.value = gradeRes.data?.data || [];
      taskTypeList.value = taskTypeRes.data?.data || [];
    } catch (error) {
      console.error("获取选项数据失败:", error);
    }
  }

  function chores(curData, res, title, done) {
    try {
      message(`${title}策略"${curData.strategy_name}"成功`, {
        type: "success"
      });
      done(); // 关闭弹框
      onSearch(); // 刷新表格数据
    } catch (error) {
      message(`${title}失败`, {
        type: "error"
      });
    }
  }

  // 处理频率数据格式
  function formatFrequencyData(row) {
    if (row?.assignment_frequency_type && row?.assignment_frequency_data) {
      return {
        assignment_frequency_type: row.assignment_frequency_type,
        assignment_frequency_data: Array.isArray(row.assignment_frequency_data) 
          ? row.assignment_frequency_data 
          : JSON.parse(row.assignment_frequency_data || '[]')
      };
    }
    // 兼容旧数据格式
    if (row?.assignment_frequency) {
      return {
        assignment_frequency_type: "weekly",
        assignment_frequency_data: [1] // 默认周一
      };
    }
    return {
      assignment_frequency_type: "weekly",
      assignment_frequency_data: [1]
    };
  }

  function openDialog(title = "新增", row?) {
    const frequencyData = row ? formatFrequencyData(row) : {
      assignment_frequency_type: "weekly",
      assignment_frequency_data: [1]
    };

    addDialog({
      title: `${title}任务策略`,
      props: {
        formInline: {
          strategy_name: row?.strategy_name ?? "",
          customer_grade_id: row?.customer_grade_id ?? null,
          task_type_id: row?.task_type_id ?? null,
          assignment_frequency_type: frequencyData.assignment_frequency_type,
          assignment_frequency_data: frequencyData.assignment_frequency_data,
          status: row?.status ?? 1,
          gradeList: gradeList.value,
          taskTypeList: taskTypeList.value
        }
      },
      width: "60%", // 增大弹窗宽度
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline;

        FormRef.validate(valid => {
          if (valid) {
            // 验证频率数据
            if (!curData.assignment_frequency_data || curData.assignment_frequency_data.length === 0) {
              message("请至少选择一个执行时间", { type: "warning" });
              return;
            }

            // 提取需要提交的数据
            const submitData = {
              strategy_name: curData.strategy_name,
              customer_grade_id: curData.customer_grade_id,
              task_type_id: curData.task_type_id,
              assignment_frequency_type: curData.assignment_frequency_type,
              assignment_frequency_data: JSON.stringify(curData.assignment_frequency_data), // 转为JSON字符串存储
              status: curData.status
            };

            if (title === "新增") {
              taskStrategyApi.create(submitData)
                .then((res: any) => {
                  if (res.success) {
                    message(`${title}策略成功`, { type: "success" });
                    done(); // 关闭弹窗
                    onSearch(); // 刷新列表
                  } else {
                    message(res.message || `${title}策略失败`, { type: "error" });
                  }
                })
                .catch(error => {
                  console.error("创建策略错误:", error);
                  const errorMsg = error.response?.data?.message || error.message || `${title}策略失败`;
                  message(errorMsg, { type: "error" });
                });
            } else {
              taskStrategyApi.update(row.id, submitData)
                .then((res: any) => {
                  if (res.success) {
                    message(`${title}策略成功`, { type: "success" });
                    done(); // 关闭弹窗
                    onSearch(); // 刷新列表
                  } else {
                    message(res.message || `${title}策略失败`, { type: "error" });
                  }
                })
                .catch(error => {
                  console.error("更新策略错误:", error);
                  const errorMsg = error.response?.data?.message || error.message || `${title}策略失败`;
                  message(errorMsg, { type: "error" });
                });
            }
          }
        });
      }
    });
  }

  function handleEdit(row) {
    openDialog("编辑", row);
  }

  async function handleDelete(row?) {
    if (row) {
      // 删除单个 - 由于模板中已有 el-popconfirm，这里直接执行删除
      try {
        await taskStrategyApi.delete(row.id);
        message(`删除策略"${row.strategy_name}"成功`, { type: "success" });
        onSearch();
      } catch (error) {
        console.error("删除策略失败:", error);
        message("删除策略失败", { type: "error" });
      }
    } else {
      // 批量删除
      const selection = tableRef.value.getTableRef().getSelectionRows();
      if (selection.length === 0) {
        message("请先选择要删除的数据", { type: "warning" });
        return;
      }

      try {
        const result = await ElMessageBox.confirm(
          `确认要删除选中的 ${selection.length} 条数据吗？`,
          "批量删除确认",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        );

        if (result === "confirm") {
          for (const item of selection) {
            await taskStrategyApi.delete(item.id);
          }
          message("批量删除成功", { type: "success" });
          onSearch();
          onSelectionCancel();
        }
      } catch (error) {
        console.log("用户取消删除");
      }
    }
  }

  async function handleEnable(row) {
    try {
      await taskStrategyApi.enable(row.id);
      message(row.status === 1 ? "禁用成功" : "启用成功", { type: "success" });
      onSearch();
    } catch (error) {
      message("操作失败", { type: "error" });
    }
  }

  async function handlePreview(row) {
    try {
      const { data } = await taskStrategyApi.preview(row.id);
      
      // 格式化频率预览信息
      const frequencyData = formatFrequencyData(row);
      let frequencyText = "";
      if (frequencyData.assignment_frequency_type === 'weekly') {
        const weekMap = { 1: "周一", 2: "周二", 3: "周三", 4: "周四", 5: "周五", 6: "周六", 7: "周日" };
        const days = frequencyData.assignment_frequency_data.map(d => weekMap[d]).filter(Boolean);
        frequencyText = `每周：${days.join('、')}`;
      } else {
        const dates = frequencyData.assignment_frequency_data.sort((a, b) => a - b).map(d => `${d}日`);
        frequencyText = `每月：${dates.join('、')}`;
      }

      const previewContent = `
        <div style="text-align: left; line-height: 1.6;">
          <p><strong>策略名称：</strong>${row.strategy_name}</p>
          <p><strong>客户等级：</strong>${row.customer_grade.name || '未知'}</p>
          <p><strong>任务类型：</strong>${row.task_type.name || '未知'}</p>
          <p><strong>执行频率：</strong>${frequencyText}</p>
          <p><strong>策略状态：</strong>${row.status === 1 ? '启用' : '禁用'}</p>
          <hr style="margin: 15px 0; border: none; border-top: 1px solid #eee;">
          <p><strong>预览信息：</strong></p>
          <p>${data.preview_message || "该策略将按照设定的频率为符合条件的客户自动分配任务"}</p>
        </div>
      `;

      ElMessageBox.alert(previewContent, "策略预览", {
        confirmButtonText: "确定",
        dangerouslyUseHTMLString: true
      });
    } catch (error) {
      message("预览失败", { type: "error" });
    }
  }

  async function handleManualAssign() {
    try {
      loading.value = true;
      const result = await taskStrategyApi.manualAssign();
      message(`手动指派完成，共分配了 ${result.data?.assigned_count || 0} 个任务`, { type: "success" });
      onSearch(); // 刷新表格
    } catch (error) {
      console.error("手动指派失败:", error);
      message("手动指派失败", { type: "error" });
    } finally {
      loading.value = false;
    }
  }

  async function handleBatchExecute() {
    const selection = tableRef.value.getTableRef().getSelectionRows();
    if (selection.length === 0) {
      message("请先选择要执行的策略", { type: "warning" });
      return;
    }

    try {
      // 显示确认对话框，列出将要执行的策略
      const strategyNames = selection.map(item => item.strategy_name).join('、');
      const result = await ElMessageBox.confirm(
        `确认要执行选中的 ${selection.length} 个策略吗？\n策略列表：${strategyNames}`,
        "批量执行策略确认",
        {
          confirmButtonText: "确定执行",
          cancelButtonText: "取消",
          type: "warning",
          customClass: "strategy-execute-confirm"
        }
      );

      if (result === "confirm") {
        loading.value = true;
        const strategyIds = selection.map(item => item.id);
        const executeResult = await taskStrategyApi.batchExecute(strategyIds);
        
        message(`批量执行完成，共分配了 ${executeResult.data?.assigned_count || 0} 个任务`, { type: "success" });
        onSearch(); // 刷新表格
        onSelectionCancel(); // 清除选择
      }
    } catch (error) {
      if (error === "cancel") {
        console.log("用户取消执行");
      } else {
        console.error("批量执行失败:", error);
        message("批量执行失败", { type: "error" });
      }
    } finally {
      loading.value = false;
    }
  }

  onMounted(async () => {
    await loadOptions();
    onSearch();
  });

  return {
    form,
    dataList,
    loading,
    columns,
    selectedNum,
    pagination,
    resetForm,
    onSearch,
    openDialog,
    handleEdit,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    onSelectionCancel,
    handleEnable,
    handlePreview,
    handleManualAssign,
    handleBatchExecute
  };
} 